package com.sunny;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class MyClassLoader extends ClassLoader {

    public MyClassLoader() {
        super(MyClassLoader.class.getClassLoader());
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        FileInputStream fis;
        FileChannel fc = null;
        ByteArrayOutputStream bos = null;

        try {
            fis = new FileInputStream(name);
            fc = fis.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int res;
            while ((res = fc.read(buffer)) != -1) {
                buffer.flip();
                String r = new String(buffer.array());
                System.out.println(r);
            }

            fis = new FileInputStream(name);
            int len = 0;
            bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        byte[] b = bos.toByteArray();
        return defineClass(null, b, 0, b.length);
    }
}
